//
//  CommentDetailVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/4/23.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "CommentDetailVC.h"
#import "CommentsCell.h"
#import "CommentVM.h"
#import "CommentsTextView.h"
#import "MJRefresh.h"
#import "ImageCell.h"
#import "ZXChatHelper.h"
#import "OtherInfoVC.h"
@interface CommentDetailVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) CommentsTextView *cTextView;
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) NSMutableArray  *commentsImages;
@end

@implementation CommentDetailVC{
    RITLPhotoNavigationViewModel * viewModel;
    CommentModel    *selectModel;
    
    NSString        *sendStr;
    NSString        *lastId;
    UIButton *btnPraise;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"评论详情";
    lastId=@"0";
    viewModel = [RITLPhotoNavigationViewModel new];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)setModel:(CommentModel *)model{
    _model=model;
    [self createUI];
    [self getData];
}

- (void)createUI{
    UIView *headView=[[UIView alloc]init];
    headView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
    }];
    
    UIImageView *headImageV =[[UIImageView alloc]init];
    headImageV.layer.masksToBounds=YES;
    headImageV.layer.cornerRadius=19;
    [headImageV sd_setImageWithURL:[NSURL URLWithString:self.model.Avater]];
    [headView addSubview:headImageV];
    [headImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView).with.offset(13);
        make.left.equalTo(headView).with.offset(7);
        make.size.mas_equalTo(CGSizeMake(38, 38));
    }];
    
    QXLable *labName=[[QXLable alloc]initTitle];
    labName.text=self.model.NickName;
    [headView addSubview:labName];
    [labName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headImageV.mas_right).with.offset(10);
        make.top.equalTo(headImageV);
    }];
    
    QXLable *labTime= [[QXLable alloc]initWithFount:13];
    labTime.text=self.model.SubTime;
    [headView addSubview:labTime];
    [labTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(labName);
        make.bottom.equalTo(headImageV);
    }];
    
    QXLable *labContent =[[QXLable alloc]initTitle];
    labContent.attributedText=[ZXChatHelper formatMessageString:self.model.Content];
    [headView addSubview:labContent];
    [labContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(labTime);
        make.right.equalTo(headView).with.offset(-20);
        make.top.equalTo(labTime.mas_bottom).with.offset(11);
    }];
    
    UIImage *imageComments=[UIImage imageNamed:@"comments"];
    UIButton *btnComments=[[UIButton alloc]init];
    [btnComments addTarget:self action:@selector(onclickReply) forControlEvents:UIControlEventTouchUpInside];
    [btnComments setImage:imageComments forState:UIControlStateNormal];
    [headView addSubview:btnComments];
    [btnComments mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(labContent);
        make.top.equalTo(labContent.mas_bottom).with.offset(16);
        make.size.mas_equalTo(CGSizeMake(20, 30));
    }];
    
    btnPraise=[[UIButton alloc]init];
    [btnPraise setImage:[UIImage imageNamed:@"praise_normal"] forState:UIControlStateNormal];
    [btnPraise setImage:[UIImage imageNamed:@"praise_select"] forState:UIControlStateSelected];
    [btnPraise setSelected:self.model.IsLike];
    [btnPraise setTitle:[NSString stringWithFormat:@" %ld",self.model.StarCount] forState:UIControlStateNormal];
    [btnPraise setTitleColor:DEFAULTTEXTBLACKCOLOR forState:UIControlStateNormal];
    [btnPraise addTarget:self action:@selector(onclickLike) forControlEvents:UIControlEventTouchUpInside];
    btnPraise.contentHorizontalAlignment=
    UIControlContentHorizontalAlignmentRight;
    [btnPraise.titleLabel setFont:[UIFont systemFontOfSize:10]];
    [headView addSubview:btnPraise];
    [btnPraise mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(btnComments.mas_left).with.offset(-10);
        make.centerY.equalTo(btnComments);
        make.size.mas_equalTo(CGSizeMake(100, 30));
    }];
    if (self.model.Pictures.count>0) {
        [headView addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(labContent);
            make.top.equalTo(btnComments.mas_bottom).with.offset(5);
            make.height.mas_equalTo(@70);
            make.bottom.equalTo(headView).with.offset(-5);
        }];
    }else{
        [headView addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(labContent);
            make.top.equalTo(btnComments.mas_bottom).with.offset(0);
            make.height.mas_equalTo(@0);
            make.bottom.equalTo(headView).with.offset(-5);
        }];
    }
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(headView.mas_bottom).with.offset(5);
    }];
}

- (void)getData{
    WS(weakSelf);
    [[CommentVM manage] getReplayListWithId:self.model.Id andType:self.type andLast:lastId Success:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.dataArr addObjectsFromArray:arr];
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    }];
}

- (void)onclickReply{
    [self replayComment:self.model];
}

- (void)onclickLike{
    [self likeComment:self.model];
}

#pragma mark -- 发布评论
- (void)publishComment{
    WS(weakSelf);
    [SVProgressHUD show];
    [self postImageWithDoneArr:[NSMutableArray new] done:^(NSMutableArray *arr) {
        
        [[CommentVM manage] publishWithId:selectModel.Id andType:self.type andContent:[[SocketRocketUtility instance] sendMessageConversion:self.cTextView.textView.text] andCommentType:self.type andPic:arr Success:^(id returnValue) {
            [self.commentsImages removeAllObjects];
            sendStr=nil;
            if (returnValue) {
                [weakSelf.dataArr insertObject:returnValue atIndex:0];
                [weakSelf.tableView reloadData];
            }
            [weakSelf.cTextView removeSelf];
            [SVProgressHUD dismiss];
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }];
}

- (void)postImageWithDoneArr:(NSMutableArray *)doneArr done:(void(^)(NSMutableArray *arr))doneBlock{
    if (doneArr.count==self.commentsImages.count) {
        doneBlock(doneArr);
        return;
    }
    WS(weakSelf);
    [[BaseVM manage] postImageWithImage:self.commentsImages[doneArr.count] andType:3 andSuccess:^(id returnValue) {
        [doneArr addObject:[returnValue objectForKey:@"ResouceId"]];
        [weakSelf postImageWithDoneArr:doneArr done:doneBlock];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 对评论进行回复
- (void)replayComment:(CommentModel *)model{
    selectModel=model;
    [self.cTextView.textView becomeFirstResponder];
}

#pragma mark -- 对评论进行点赞
- (void)likeComment:(CommentModel *)model{
    self.tableView.userInteractionEnabled=NO;
    WS(weakSelf);
    [[CommentVM manage] clickLikeWithId:model.Id andType:self.type andOperationType:model.IsLike?2:1 Success:^(id returnValue) {
        [weakSelf refreshPraise:model];
    } andFail:^(NSString *errorMessage, NSError *error) {
        weakSelf.tableView.userInteractionEnabled=YES;
    }];
}

- (void)refreshPraise:(CommentModel *)model{
    model.IsLike=!model.IsLike;
    if (model.IsLike) {
        model.StarCount+=1;
    }else{
        model.StarCount-=1;
    }
    [btnPraise setSelected:self.model.IsLike];
    [btnPraise setTitle:[NSString stringWithFormat:@" %ld",self.model.StarCount] forState:UIControlStateNormal];
    self.tableView.userInteractionEnabled=YES;
    [self.tableView reloadData];
}


#pragma mark -- 选择照片
- (void)selectPic{
    
    if (self.commentsImages.count>2) {
        [SVProgressHUD showErrorWithStatus:@"最多只能上传3张图片"];
        return;
    }
    
    sendStr=self.cTextView.textView.text;
    [self.cTextView removeSelf];
    UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];;
    UIAlertAction *albumAction=[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WS(weakSelf);
        viewModel.RITLBridgeGetImageBlock = ^(NSArray  * images){
            for (NSDictionary *dict in images) {
                [weakSelf.commentsImages addObject:[dict objectForKey:@"image"]];
            }
            [weakSelf.cTextView.textView becomeFirstResponder];
        };
        self.hidesBottomBarWhenPushed = NO;
        viewModel.maxNumberOfSelectedPhoto=3-self.commentsImages.count;
        RITLPhotoNavigationViewController * viewController = [RITLPhotoNavigationViewController photosViewModelInstance:viewModel];
        [self presentViewController:viewController animated:true completion:^{}];
    }];
    UIAlertAction *cameraAction=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
        ipc.delegate = self;
        ipc.sourceType = sourceType;
        [self presentViewController:ipc animated:YES completion:nil];
    }];
    [alertCtrl addAction:cancleAction];
    [alertCtrl addAction:albumAction];
    [alertCtrl addAction:cameraAction];
    [self presentViewController:alertCtrl animated:YES completion:nil];
}

#pragma mark - tableView输入框遮挡
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(keyboardTop+(SCREEN_WIDTH-60)/6+10+HEIGHT_CHATBOXVIEW-(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6+5:0)));
    }];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
    }];
    [UIView commitAnimations];
    
}

#pragma mark -- UINavigationControllerDelegate, UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (!self.commentsImages) {
        self.commentsImages=[[NSMutableArray alloc]init];
    }
    [self.commentsImages addObject:image];
    [self dismissViewControllerAnimated:YES completion:^{
        [self.cTextView.textView becomeFirstResponder];
    }];
    
    
}

#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentModel *model=self.dataArr[indexPath.row];
    model.ReplayCount=0;
    WS(weakSelf);
    if (model.ReplayCount>0) {
        CommentsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CommentsCell" forIndexPath:indexPath];
        [cell setModel:model];
        cell.likeComment = ^(CommentModel *model) {
            [weakSelf likeComment:model];
        };
        cell.replayComment = ^(CommentModel *model) {
            [weakSelf replayComment:model];
        };
        cell.lookUser = ^(CommentModel *model) {
//            OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//            vc.userId=model.ParentComment.UserId;
//            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
    CommentsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CommentsCell1" forIndexPath:indexPath];
    [cell setModel:model];
    cell.likeComment = ^(CommentModel *model) {
        [weakSelf likeComment:model];
    };
    cell.replayComment = ^(CommentModel *model) {
        [weakSelf replayComment:model];
    };
    cell.lookUser = ^(CommentModel *model) {
//        OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//        vc.userId=model.ParentComment.UserId;
//        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - collectionView代理函数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.model.Pictures.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREEN_WIDTH-80)/3.0, 60);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
    [cell.imageV sd_setImageWithURL:self.model.Pictures[indexPath.row]];
    return cell;
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 0, 5, 0);
}


#pragma mark -- 懒加载
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[[NSMutableArray alloc]init];
    }
    return _dataArr;
}

- (UICollectionView *)collectionView{
    if (_collectionView==nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake((SCREEN_WIDTH-85)/3.0, 60)];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 10.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator=NO;
        [_collectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"ImageCell"];
    }
    return _collectionView;
}


- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=[UIColor whiteColor];
        [_tableView registerClass:[CommentsCell class] forCellReuseIdentifier:@"CommentsCell"];
        [_tableView registerClass:[CommentsCell class] forCellReuseIdentifier:@"CommentsCell1"];
        _tableView.estimatedRowHeight=150.0f;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            lastId=@"0";
            [weakSelf.dataArr removeAllObjects];
            [weakSelf.tableView reloadData];
            [weakSelf getData];
        }];
        _tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            CommentModel *model=weakSelf.dataArr.lastObject;
            lastId=model.Id;
            [weakSelf getData];
        }];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(weakSelf.view);
            
        }];
        
    }
    return _tableView;
}

     
- (CommentsTextView *)cTextView{
    if (!_cTextView) {
        WS(weakSelf);
        _cTextView=[[CommentsTextView alloc]init];
        _cTextView.textView.text=sendStr;
        [_cTextView setImageArr:self.commentsImages];
        _cTextView.clickEmj = ^(BOOL isFace) {
            if (isFace) {
                [weakSelf.cTextView.textView resignFirstResponder];
                [weakSelf.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
                }];
            }else{
                [weakSelf.cTextView.textView becomeFirstResponder];
            }
        };
        _cTextView.showPic = ^ {
            [weakSelf selectPic];
        };
        
        _cTextView.sendBlock = ^{
            [weakSelf publishComment];
            
        };
        _cTextView.removeBlock = ^{
            [weakSelf.cTextView removeFromSuperview];
            weakSelf.cTextView=nil;
        };
        [self.view addSubview:_cTextView];
        
        [_cTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            make.height.mas_equalTo(@0);
        }];
        
    }
    return _cTextView;
}

- (NSMutableArray *)commentsImages{
    if (!_commentsImages) {
        _commentsImages=[[NSMutableArray alloc]init];
    }
    return _commentsImages;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end
     
     
